package com.jiaxu.qqmusic;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import java.io.IOException;
import java.util.List;

public class MyService extends Service {
    private MediaPlayer player;
    List<Mp3Info> mp3Infos;
    Handler handler = new Handler();

    public MyService() {
    }

    @Override
    public void onCreate() {
        mp3Infos = new MediaUtils(this).getMp3Infos();
        String url = mp3Infos.get(1).getUrl();
        player = new MediaPlayer();

        player.start();
//        Runnable autoPlay = new Runnable() {
//            @Override
//            public void run() {
//                if(!player.isPlaying()){
//                    player.reset();
//                    try {
//                        player.setDataSource("qew");
//                        player.prepare();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//
//            }
//            handler.postDelayed(autoPlay,0);
//        };

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        int action = intent.getIntExtra("action", -1);
        String url = intent.getStringExtra("url");
        switch (action) {
            case MainActivity.PLAY:
                player.start();
                break;
            case MainActivity.PAUSE:
                player.pause();
                break;
            case MainActivity.CHANGE:
                player.reset();
                try {
                    player.setDataSource(url);
                    player.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                player.start();
                break;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    public class Mybinder extends Binder {
        private int progress = 100;
        private int duration;

        public int getProgress() {
            progress = player.getCurrentPosition();
            return progress;
        }

        public int getDuration() {
            duration = player.getDuration();
            return duration;
        }

        public void setProgress(int progress) {
            player.seekTo(progress);
        }

    }

    @Override
    public IBinder onBind(Intent intent) {
        return new Mybinder();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        player.stop();
        player.release();
    }
}
